package com.phuoc.dao;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.phuoc.entities.TypeOfFood;

public class TypeOfFoodDAO {
	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allCols = { 
			MySQLiteHelper.TYPE_FOOD_ID,
			MySQLiteHelper.TYPE_FOOD_NAME};
	
	public TypeOfFoodDAO(Context context){
		dbHelper = new MySQLiteHelper(context);
	}
	
	// Open connection
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	// Close connection
	public void close() {
		dbHelper.close();
	}
	
	// Create type of food
	public void createTypeOfFood(String name) {
		// ContentValues to hold our establishment
		ContentValues values = new ContentValues();
		
		// Add a value to a set
		values.put(MySQLiteHelper.TYPE_FOOD_NAME, name);

		database.insert(MySQLiteHelper.TABLE_TYPE_OF_FOOD, null, values);
	}
	
	// checking name type of Establishment is exists ?
	public boolean checkNameExists(String name){
	Cursor cs =	database.query(MySQLiteHelper.TABLE_TYPE_OF_FOOD, 
			allCols, MySQLiteHelper.TYPE_FOOD_NAME + " = '" + name + "'", null, null, null, null);
	
		if(cs.getCount() > 0){
			cs.close();
			return true;
		}else{
			cs.close();
			return false;
		}
	}
	
	// Get all name type of establishment
	public ArrayList<String> getAllTypeOfFood(){
		ArrayList<String> nameTypeFoods = new ArrayList<String>();
		Cursor cs = database.query(MySQLiteHelper.TABLE_TYPE_OF_FOOD, allCols, null, null, null, null, null);
		while(cs.moveToNext()){
			nameTypeFoods.add(cursorToTypeOfFood(cs).getName());
		}
		cs.close();
		return nameTypeFoods;
	}
	
	// get id by name 
	public long getIdByName(String name){
		Cursor cs = database.query(MySQLiteHelper.TABLE_TYPE_OF_FOOD, 
				allCols, 
				MySQLiteHelper.TYPE_FOOD_NAME + " = '" + name + "'", null, null, null, null);
		if(cs.getCount() > 0){
			cs.moveToFirst();
			TypeOfFood typeFood = cursorToTypeOfFood(cs);
			cs.close();
			return typeFood.getId();
		}
		else{
			cs.close();
			return -1;
		}
	}
	
	// get name by id
	public String getNameById(long id){
		Cursor cs = database.query(MySQLiteHelper.TABLE_TYPE_OF_FOOD, 
				allCols, 
				MySQLiteHelper.TYPE_FOOD_ID + " = " + id, null, null, null, null);
		cs.moveToFirst();
		TypeOfFood typeFood = cursorToTypeOfFood(cs);
		cs.close();
		return typeFood.getName();
	}
	
	// convert cursor to type of establishment
	public TypeOfFood cursorToTypeOfFood(Cursor cs){
		TypeOfFood typeFood = new TypeOfFood();
		typeFood.setId(cs.getLong(0));
		typeFood.setName(cs.getString(1));
		
		return typeFood;
	}
}
